/**
 * 手动任务脚本
 * 更新我的客户信息表，从“企微添加客户”表同步，根据员工id和客户id匹配
 */
(function() {
  var applicationId = $.context.getCurrentApplicationId();
  var currentUser = $.context.getCurrentUser();
  var userId = currentUser.getWxUserId();
  
  // 从企微客户列表获取我的客户
  function getCustomerList() {
    var formName = "企微添加客户";
    // 从企业微信客户表单获取该员工下的客户
    var conditionMap = new Packages.java.util.HashMap();
    conditionMap.put("员工", userId);
    var list = $.form.getDocumentsByCondition(
      applicationId,
      formName,
      conditionMap
    );
    return list
  }

  // 获取我的客户信息表实例
  function getMyCustomerList() {
    var formName = "客户信息";
    // 从企业微信客户表单获取该员工下的客户
    var conditionMap = new Packages.java.util.HashMap();
    var list = $.form.getDocumentsByCondition(
      applicationId,
      formName,
      conditionMap
    );
    return list
  }

  function getMyCustomerListId(list) {
    var ids = [];
    if (list.size() > 0) {
      for (var i = 0; i < list.size(); i++) {
        var id = list.get(i).getElementByName("客户id").getValue();
        ids.push(String(id));
      }
    }
    return ids;
  }

  var customerList = getCustomerList();
  var myCustomerList = getMyCustomerList();

  // 客户id列表
  var myCustomerIds = getMyCustomerListId(myCustomerList);

  // 遍历导入
  if (customerList.size() > 0) {
    for (var i = 0; i < customerList.size(); i++) {
      var item = customerList.get(i);
      var extId = String(item.getElementByName('客户').getValue());
      var doc = $.form.createEmptyDocument(applicationId, "客户信息");
      if (myCustomerIds.indexOf(extId) < 0) {
        doc.addElement("客户id", item.getElementByName("客户").getValue());
      } else {
        // 如果已经有这个客户，直接覆盖原来的数据
        doc = myCustomerList.get(myCustomerIds.indexOf(extId));
      }
      doc.addElement("联系电话", item.getElementByName("客户电话").getValue());
      doc.addElement("客户名称", item.getElementByName("姓名").getValue());
      doc.addElement("分配状态", "2");
      doc.addElement("负责人", currentUser.id);
      $.form.saveFormDocument(doc, applicationId);
    }
  }
})()
